package com.hqj.exception;

import com.hqj.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author 黄啟军
 * @version 1.0
 * @date 2020/8/2 0002
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**实体校验异常
     * HttpStatus.UNAUTHORIZED--返回的状态码
     * */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e){
        log.error("实体校验异常",e);
        BindingResult result = e.getBindingResult();
        //可以连续抛两种
        ObjectError objectError = result.getAllErrors().stream().findFirst().get();
        return Result.error(objectError.getDefaultMessage());
    }
    /**无权限异常*/
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = ShiroException.class)
    public Result handler(ShiroException e){
        log.error("认证异常",e);
        return Result.error(e.getMessage());
    }
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e){
        log.error("运行时异常",e);
        return Result.error(e.getMessage());
    }
    /**用户为空异常*/
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e){
        log.error("用户为空异常",e);
        return Result.error(e.getMessage());
    }
}
